import { Component, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';

import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppService } from '../../services/app.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { delay, first } from 'rxjs';
import { SidebarComponent } from '../../modules/sidebar/sidebar.component';
import { trigger } from '@angular/animations';

@Component({
  selector: 'app-edit-plugins',
  standalone: true,
  imports: [SidebarComponent, RouterModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
    HttpClientModule,],
  templateUrl: './edit-plugins.component.html',
  styleUrl: './edit-plugins.component.scss'
})
export class EditPluginsComponent implements OnInit {
  [x: string]: any;
  public URL: string = "http://localhost/REST_API/";

  public updatePluginForm: FormGroup;
  public selectedImage!: File;
  public selectedFolder!: File;
  public plugin_id: any;
  public pluginListByID: any = [];
  public pluginListSubcribe: any;
  public Image_Url: any;
  public Folder_Dowload: any;

  constructor(private fb: FormBuilder, private appService: AppService, private router: Router, private route: ActivatedRoute) {
    this.updatePluginForm = this.fb.group({
      plugin_name: ['', Validators.required],
      plugin_detail: ['', Validators.required],
      price: ['', Validators.required],
    });

  }
  async ngOnInit() {
    this.plugin_id = await this.route.snapshot.paramMap.get('plugin_id');
    this.pluginListSubcribe = await this.appService.loadPluginByID(this.plugin_id).subscribe(res => {
      this.pluginListByID = res;
      this.Image_Url = this.pluginListByID.plugins[0].image_url;
      this.Folder_Dowload = this.pluginListByID.plugins[0].folder_dowload;
    });

  }

  async onChangeImage(event: any) {
    if (event.target.files && event.target.files.length > 0) {
      this.selectedImage = event.target.files[0];
    }
  }

  async uploadImage(name: any) {
    const form: HTMLFormElement | null = document.querySelector("form"),
      fileInput = form?.querySelector(".file-image");

    if (form && fileInput) {
      let xhr: XMLHttpRequest = new XMLHttpRequest();
      xhr.open("POST", this.URL + '/upload_image.php');
      let formData: FormData = new FormData(form);
      xhr.send(formData);
    }

  }

  async onChangeFolder(event: any) {
    if (event.target.files && event.target.files.length > 0) {
      this.selectedFolder = event.target.files[0];
    }
  }

  async uploadFolder(name: any) {
    const form: HTMLFormElement | null = document.querySelector("form"),
      fileInput = form?.querySelector(".file-folder");

    if (form && fileInput) {
      let xhr: XMLHttpRequest = new XMLHttpRequest();
      xhr.open("POST", this.URL + '/upload_folder.php');
      let formData: FormData = new FormData(form);
      xhr.send(formData);
    }

  }

  async updatePluginByID(updatePluginForm: any) {
    if (this.selectedImage && !this.selectedFolder) {
      this.plugin_id = this.route.snapshot.paramMap.get('plugin_id');
      if (updatePluginForm.valid) {
        this.appService.updatePluginByID(
          this.plugin_id,
          updatePluginForm.value.plugin_name,
          updatePluginForm.value.plugin_detail,
          updatePluginForm.value.price,
          this.selectedImage.name,
          this.Folder_Dowload,
        ).pipe(first())
          .subscribe(data => {
            console.log(data);
            if (data.message == 'Update Plugin Success') {
              alert('แก้ไข Plugins สำเร็จ');
              this.router.navigate(['/admin-page']);
            }
            if (data.message == 'Update Plugin Falied') {
              alert('แก้ไข Plugins ไม่สำเร็จ');
            }
          }, error => {
            alert("แก้ไข Plugins ไม่สำเร็จ");
          })
      }
      this.uploadImage(this.selectedImage.name);
    }
    if (!this.selectedImage && this.selectedFolder) {
      this.plugin_id = this.route.snapshot.paramMap.get('plugin_id');
      if (updatePluginForm.valid) {
        this.appService.updatePluginByID(
          this.plugin_id,
          updatePluginForm.value.plugin_name,
          updatePluginForm.value.plugin_detail,
          updatePluginForm.value.price,
          this.Image_Url,
          this.selectedFolder.name,
        ).pipe(first())
          .subscribe(data => {
            console.log(data);
            if (data.message == 'Update Plugin Success') {
              alert('แก้ไข Plugins สำเร็จ');
              this.router.navigate(['/admin-page']);
            }
            if (data.message == 'Update Plugin Falied') {
              alert('แก้ไข Plugins ไม่สำเร็จ');
            }
          }, error => {
            alert("แก้ไข Plugins ไม่สำเร็จ");
          })
      }
      this.uploadFolder(this.selectedFolder.name);
    }
    if (!this.selectedImage && !this.selectedFolder) {
      this.plugin_id = this.route.snapshot.paramMap.get('plugin_id');
      if (updatePluginForm.valid) {
        this.appService.updatePluginByID(
          this.plugin_id,
          updatePluginForm.value.plugin_name,
          updatePluginForm.value.plugin_detail,
          updatePluginForm.value.price,
          this.Image_Url,
          this.Folder_Dowload,
        ).pipe(first())
          .subscribe(data => {
            console.log(data);
            if (data.message == 'Update Plugin Success') {
              alert('แก้ไข Plugins สำเร็จ');
              this.router.navigate(['/admin-page']);
            }
            if (data.message == 'Update Plugin Falied') {
              alert('แก้ไข Plugins ไม่สำเร็จ');
            }
          }, error => {
            alert("แก้ไข Plugins ไม่สำเร็จ");
          })
      }
    } else {
      this.plugin_id = this.route.snapshot.paramMap.get('plugin_id');
      if (updatePluginForm.valid) {
        this.appService.updatePluginByID(
          this.plugin_id,
          updatePluginForm.value.plugin_name,
          updatePluginForm.value.plugin_detail,
          updatePluginForm.value.price,
          this.selectedImage.name,
          this.selectedFolder.name,
        ).pipe(first())
          .subscribe(data => {
            console.log(data);
            if (data.message == 'Update Plugin Success') {
              alert('แก้ไข Plugins สำเร็จ');
              this.router.navigate(['/admin-page']);
            }
            if (data.message == 'Update Plugin Falied') {
              alert('แก้ไข Plugins ไม่สำเร็จ');
            }
          }, error => {
            alert("แก้ไข Plugins ไม่สำเร็จ");
          })
      }
      this.uploadImage(this.selectedImage.name);
      this.uploadFolder(this.selectedFolder.name);
    }
    if (!updatePluginForm.valid) {
      alert("กรุณากรอกให้ครบ");
    }
  }

  async deletePlugin() {
    this.plugin_id = this.route.snapshot.paramMap.get('plugin_id');
    this.appService.deletePluginByID(this.plugin_id).pipe(first()).subscribe(data => {
      if (data.message == 'Delete Plugin Successful') {
        alert('ลบ Plugins สำเร็จ');
        this.router.navigate(['/admin-page']);
      }
      if (data.message == 'Delete Plugin Falied') {
        alert('ลบ Plugins ไม่สำเร็จ');
      }
    });
  }

  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}